package com.zyx.javademo.time.timedemo;

import org.mapstruct.Named;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author Yaxi.Zhang
 * @since 2021/5/10 13:14
 * desc: Time相关api测试类
 */
public class TimeDemo {

    private static final String DATETIME_FORMAT_STR = "yyyy-MM-dd HH:mm:ss";

    public static void main(String[] args) {
        long ts = Instant.now().toEpochMilli();
        String str = timestampByString(ts);
        System.out.println(ts);
        System.out.println(str);

        // System.out.println(longByDtf(str));
        System.out.println(longByDtf(str));

    }

    public static String timestampByString(long ts) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DATETIME_FORMAT_STR);
        Instant ins = Instant.ofEpochMilli(ts);
        ZonedDateTime zdt = ins.atZone(ZoneId.systemDefault());
        return dtf.format(zdt);
    }

    public static long longByDtf(String dtfStr) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DATETIME_FORMAT_STR);
        ZonedDateTime zdt = LocalDateTime.parse(dtfStr, dtf).atZone(ZoneId.systemDefault());
        return zdt.toInstant().toEpochMilli();
    }
}
